import sys
import time
import os
import thread
import traceback


SEV_DEBUG = 10
SEV_INFO = 20
SEV_WARNING = 30
SEV_STATUS = 40
SEV_ERROR = 50
SEV_EXCEPTION = 60
SEV_FATAL = 100


logdevice = sys.stdout
ignore_labels = set()
ignore_sources = set()
min_sevitiry = SEV_STATUS
show_sevirity = False
show_source = True
show_label = True
show_date = False
show_time = False
show_pid = False
show_tid = False



def log(sevirity, source, label, msgfmt, *args):
    if sevirity < min_sevitiry:
        return
    if source in ignore_sources:
        return
    if label in ignore_labels:
        return
    if args:
        msgtext = msgfmt % args
    else:
        msgtext = msgfmt
    tags = []
    if show_sevirity:
        tags.append("(%2d)" % sevirity)
    if show_source:
        tags.append("%-10s" % source)
    if show_label:
        tags.append("%-10s" % label)
    if show_time:
        tags.append(time.strftime("%H:%M:%S"))
    if show_date:
        tags.append(time.strftime("%y.%m.%d"))
    if show_pid:
        tags.append("pid=%4d" % os.getpid())
    if show_tid:
        tags.append("tid=%4d" % thread.get_ident())
    if tags:
        tagstext = "[" + " ".join(tags) + "] "
    else:
        tagstext = ""
    text = "%s%s\n" % (tagstext, msgtext)
    logdevice.write(text)
    logdevice.flush()


def logdebug(label, msgfmt, *args):
    log(SEV_DEBUG, "gabot", label, msgfmt, *args)

def loginfo(label, msgfmt, *args):
    log(SEV_INFO, "gabot", label, msgfmt, *args)

def logwarning(label, msgfmt, *args):
    log(SEV_WARNING, "gabot", label, msgfmt, *args)

def logstat(label, msgfmt, *args):
    log(SEV_STATUS, "gabot", label, msgfmt, *args)

def logexc(label, excinfo = None):
    if excinfo is None:
        excinfo = sys.exc_info()
        if excinfo is None:
            raise ValueError("logexc must be called in the context of " 
                "an exception")
    msg = "".join(traceback.format_exception(*exc_info))
    log(SEV_EXCEPTION, "gabot", label, msg)

def logfatal(label, msgfmt, *args):
    log(SEV_FATAL, "gabot", label, msgfmt, *args)
    sys.exit()












